<template>
  <!-- 分类管理 -->
  <div class="class">
    <avue-crud
      :option="tableOption"
      :data="storelist.data"
      v-model:page="page"
      @size-change="sizeChange"
      @current-change="currentChange"
    >
      <template #menu-left="{}">
        <el-button
          type="primary"
          color="#02A1E9"
          icon="el-icon-plus"
          @click="addGroup"
          class="paddingbtn"
          >新增</el-button>
        
      </template>
      <template #pic="scope">
        <img :src="scope.row.pic" alt="" class="img1" @error="image(scope.row)"/>
      </template>
      <template #status="scope">
        <el-tag v-if="scope.row.status === 0" size="small" type="danger">不正常</el-tag>
        <el-tag v-else size="small">正常</el-tag>
      </template>
      <template #menu="{ row }">
        <el-button type="primary" icon="el-icon-edit" @click="editGroup(row)">编辑</el-button>
          
        
        <el-button
          type="danger"
          icon="el-icon-delete"
          @click="del(row.categoryId)"
          >删除</el-button>
        
      </template>
    </avue-crud>
    <el-dialog
      v-model="dialogVisible"
      :title="flag === true ? '新增' : '编辑'"
      width="700px">
      <el-form :model="form" label-width="120px" :rules="dataRule">
        <el-form-item label="分类图片">
          <el-upload
            class="avatar-uploader"
            action="http://111.67.198.176:8111/admin/file/upload/element"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            v-model="form.pic"
            prop="pic">
          
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" />
        </el-form-item>
        <el-form-item label="上级分类">
          <el-cascader
            :options="storelist.data"
            v-model="selsectlist"
            @change="handeleHand"
            :props="categoryTreeProps"
            clearable/>
          
        </el-form-item>
        <el-form-item label="排序号">
          <el-input-number
            v-model="form.seq"
            :min="0"
            controls-position="right"
            size="large"/>
          
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="1">正常</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="comfir"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<script lang='ts' setup>
import request from "../../../../utils/request";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import { ref, reactive ,inject} from "vue";
import type { UploadProps } from "element-plus";
import { classlist } from "../../../../store/classlist";
import { tableOption } from "../../../../curd/prodClass";
import {del_fendelete,get_classlist} from '../../../../api/list'
import {treeDataTranslate} from '../../../../utils/treeDataTranslate'


const reload = inject("reload");

let storelist = classlist();
const getlist = async () => {
  const res = await get_classlist({});
  //@ts-ignore
  storelist.data = treeDataTranslate(res.data, "categoryId", "parentId");
  storelist.data.map((item: { pic: string }) => {
    item.pic = `https://assets.yiluxdeng.com/` + item.pic;
  });
};
getlist();

const imageUrl = ref("");
const img =
  "https://assets.yiluxdeng.com/blob:http://127.0.0.1:5173/0394a090-8130-4aa5-a1c9-9fa430ab8740";
const image = (data: any) => {
  data.pic = img;
};


const page = ref({
  currentPage: 1, //当前页数
  pageSize: 10, //每页显示条目个数
  total: 0, //总条目数
});
const form = reactive({
  categoryName: "", //分类名称
  status: "0", //状态
  seq: "", //排序
  pic: "",
  categoryId: "",
  grade: 0,
  parentId: 0,
});
const flag = ref(false);
const dialogVisible = ref(false);
const dataRule = reactive({
  categoryName: [
    { required: true, message: "分类名称不能为空", trigger: "blur" },
  ],
  pic: [{ required: true, message: "分类图片不能为空", trigger: "blur" }],
});


const headers = {Authorization:localStorage.getItem('token')}


//上传图片
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = form.pic;
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};
const selsectlist = ref([]) as any;
const categoryTreeProps = ref({
  value: "categoryId",
  label: "categoryName",
});
const handeleHand = () => {};

//表单确认按钮
const comfir = async () => {
  if (selsectlist.length === 1) {
    form.grade = 0;
  }
  if (selsectlist.length === 2) {
    form.grade = 1;
  }
  if (selsectlist.length === 3) {
    form.grade = 2;
  }
  if (flag.value) {
    const add_List = (params: any) => {
      axios({
        method: "post",
        url: "https://yami-admin-api.yiluxdeng.com/prod/category",
        headers: {
          Authorization:
            "iyn0X99X6B2ff0USMieWd79dJ/JsbZd+qFy2+3gjV8rsFvarFyDiwBrV618TgDw0",
        },
        data: params,
      });
    };
    add_List({ ...form });
  } else {
    console.log(111, "bianji");
    const edit_list = (params: any) => {
      axios({
        method: "PUT",
        url: "https://yami-admin-api.yiluxdeng.com/prod/category",
        headers: {
          Authorization:
            "iyn0X99X6B2ff0USMieWd79dJ/JsbZd+qFy2+3gjV8rsFvarFyDiwBrV618TgDw0",
        },
        data: params,
      });
    };
    edit_list({ ...form });
  }
  dialogVisible.value = false;
  getlist();
};

// 点击每页多少条

const sizeChange = () => {};
//点击页码
const currentChange = () => {};

//新增
const addGroup = () => {
  dialogVisible.value = true;
  flag.value = true;
  (form.categoryName = ""), (form.status = "1"), (form.seq = "");
  form.pic = "";
};
//编辑
const editGroup = (row: any) => {
  dialogVisible.value = true;
  flag.value = false;
  form.categoryName = row.categoryName;
  form.status = String(row.status);
  form.seq = String(row.seq);
  form.categoryId = row.categoryId;
  form.pic = row.pic;
};

//删除
const del = (categoryId: number) => {
    ElMessageBox.confirm("确定进行删除操作？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async => {
    del_fendelete([categoryId])
    getlist()
     //@ts-ignore
     reload();
      ElMessage({
        type: "success",
        message: "删除成功",
      });
  })
 
};

</script>

<style lang='scss'>
.classify {
  width: 99%;
  height: 100%;
  margin-left: 10px;
  background: #fff;
  margin-top: 5px;
}
.img1 {
  width: 200px;
  height: 80px;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.paddingbtn {
  margin-left: 20px;
  margin-top: 20px;
}
</style>